package com.huika.dealontop.utils;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.huika.dealontop.R;

import java.util.Locale;

/**
 * author:zwy
 */
public class SelectLanguageUtils {
    public static final String PRE_LANG = "lang";
    public static final String LANG_TH = "th";
    public static final String LANG_ZH = "zh";
    public static final String LANG_EN = "en";
    public static String LANG_AUTO = "auto";

//	public static String getCurrentLanguage() {
//		return PreferencesHelper.getString(PRE_LANG);
//	}

    public static void setLanguage(Context context) {
        String language = PreferencesHelper.getInstance().getString(PRE_LANG);
        if (TextUtils.isEmpty(language)) {
            language = getSystemLang(context);
            if (!LANG_TH.equals(language)){
                language = LANG_EN;
            }
            PreferencesHelper.setString(PRE_LANG, language);
        }

        Resources resources = context.getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        if (language.equals(LANG_EN)) {
            config.locale = Locale.ENGLISH;
        } else if (language.equals(LANG_ZH)) {
            config.locale = Locale.SIMPLIFIED_CHINESE;
        } else {
            config.locale = new Locale("th", "th");
        }
        resources.updateConfiguration(config, dm);
    }

    public static String getSystemLang(Context context) {
//		Locale locale = context.getResources().getConfiguration().locale;
//		String language = locale.getLanguage();
        String language = Locale.getDefault().getLanguage();
        if (language.contains(LANG_EN)) {
            return LANG_EN;
        } else if (language.contains(LANG_TH)) {
            return LANG_TH;
        } else if (language.contains(LANG_ZH)) {
            return LANG_ZH;
        }
        return LANG_ZH;
    }

    public static String getCurrentLanguageCode(Context context) {
        String language = PreferencesHelper.getInstance().getString(PRE_LANG);
        if (TextUtils.isEmpty(language)) {
            language = getSystemLang(context);
            PreferencesHelper.setString(PRE_LANG, language);
        }
        return language;
    }

    public static String getCurrentLanguage(Context context) {
        String language = PreferencesHelper.getInstance().getString(PRE_LANG);
        if (LANG_ZH.equals(language)) {
            return context.getResources().getString(R.string.lang_zh);
        } else if (LANG_EN.equals(language)) {
            return context.getResources().getString(R.string.lang_en);
        } else if (LANG_TH.equals(language)) {
            return context.getResources().getString(R.string.lang_th);
        } else {
            return context.getResources().getString(R.string.lang_th);
        }
    }

}
